package com.wzq.design.business.base.dept.service;

import com.wzq.design.base.service.CommService;
import com.wzq.design.business.base.dept.dto.BaseDeptDto;
import com.wzq.design.business.base.dept.dto.BaseDeptTreeDto;
import com.wzq.design.business.base.dept.entity.BaseDept;
import com.wzq.design.business.base.dept.mapper.DeptMapper;
import com.wzq.ssm.parent.util.EntityUtil;
import com.wzq.ssm.parent.util.TreeUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Objects;

/**
 * (BaseDept)表服务实现类
 *
 * @author wangzhiqiang
 * @since 2023-06-20 11:02:12
 */
@Service
public class BaseDeptService extends CommService<DeptMapper, BaseDept> {
    private final DeptMapper deptMapper;

    public BaseDeptService(DeptMapper deptMapper) {
        this.deptMapper = deptMapper;
    }


    /**
     * 获取部门树 节点
     *
     * @return 结果
     */
    public List<BaseDeptTreeDto> listTree() {
        List<BaseDept> list = deptMapper.list();

        List<BaseDeptTreeDto> treeList = EntityUtil.castDtoToModel(list, BaseDeptTreeDto.class);

        return TreeUtil.build(treeList);
    }


    @Transactional
    public BaseDeptDto save(BaseDeptDto dto) {
        BaseDept baseDept;
        if (StringUtils.isBlank(dto.getId())) {
            baseDept = EntityUtil.castDtoToModel(dto, BaseDept.class);
            setParentIds(baseDept);
            deptMapper.insert(baseDept);
        } else {
            baseDept = deptMapper.selectById(dto.getId());
            String oldParentId = baseDept.getParentId();
            EntityUtil.copyDtoToBean(dto, baseDept);
            if (!Objects.equals(oldParentId, dto.getParentId())) {
                setParentIds(baseDept);
            }
            deptMapper.updateById(baseDept);
        }

        return EntityUtil.castDtoToModel(baseDept, BaseDeptDto.class);
    }


    public BaseDeptDto findById(String id) {
        BaseDept baseDept = deptMapper.selectById(id);
        return EntityUtil.castDtoToModel(baseDept, BaseDeptDto.class);
    }


}
